import socket,gevent,struct
from gevent import socket,monkey

monkey.patch_all()

class QCSNode:
    def __init__(self):
        self.history = []
        self.prot = 8001
        self.host = "0.0.0.0"
        self.prot_switching = None
        self.size = 1024
        self.fmt = "2s18s"

    def handle_request(self, c, s):
        while True:
            data = c.recv(1024)

            if not data:
                c.close()
                break
            
            # 开始解包
            newData = struct.unpack(self.fmt, data)
            tag, message = str(newData[0], encoding="utf-8"), str(newData[1], encoding="utf-8")
            # print(tag)
            # print(type(s))
            print("正在处理%s用户的请求"%str(s))
            if tag == "TS":
                gevent.spawn(self.onProtThreshold, message)
            elif tag == "CS":
                gevent.spawn(self.onCommitSwitch, message)
            elif tag == "CA":
                gevent.spawn(self.onCommitAbort, message)
            elif tag == "TE":
                gevent.spawn(self.onTimerExpire, message)
                
            elif tag == "RH":
                gevent.spawn(self.onReceiveHistory, message)
                
            elif tag == "CH":
                gevent.spawn(self.onCommitHistory, message)
                                        
            else:
                print("404")

        
    def initialize(self):
        s=socket.socket()
        s.bind((self.host,self.prot))
        s.listen(500)
        print('开始监听500端口')

        while True:
            cli,addr=s.accept()
            print(f"{addr}客户端已连接")
            # self.clients.addend(addr)
            gevent.spawn(self.handle_request, cli, addr)

        s.close()
    
    def onProtThreshold(self, c):
        print('开始执行TS函数，message为%s'%c)
    
    def onCommitSwitch(self, c):
        print('开始执行CS函数，message为%s'%c)

    def onCommitAbort(self, c):
        print('开始执行CA函数，message为%s'%c)
    
    def onTimerExpire(self, c):
        print('开始执行TE函数，message为%s'%c)

    def onReceiveHistory(self, c):
        print('开始执行RH函数，message为%s'%c)
    
    def onCommitHistory(self, c):
        print('开始执行CH函数，message为%s'%c)
        


if __name__=='__main__':
    q = QCSNode()
    q.initialize()
